const express = require("express");
// 引入multer
var multer = require('multer');
// 引入connect-multiparty中间件
var multipart = require("connect-multiparty");
// 创建中间件对象
var multipartMiddleware = multipart();
// 引入数据库配置
const db = require("../mysql");
// 创建路由对象
const upload = express.Router();

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, `public/images/`)
    },
    filename: function (req, file, callback) {
        fileName = `${Date.now()}.png`
        callback(null, fileName);
    }
})
var uploadImg = multer({ storage: storage })

upload.post('/images', uploadImg.single('file'), function (req, res, next) {
    // res.send({ 'img': `/img/${req.body.dir}/${fileName}` })
    console.log(req.file.path);
    res.json({status:200,message:'上传成功',path:req.file.path})
});

upload.post('/book', multipartMiddleware, function (req, res, next) {
    console.log(req.body);
    const sqlStr = `insert into books (book_name,book_cover,book_category_id,book_author,book_press,book_price_yuanjia,book_price_xianjia,book_remarks,book_num,book_date,book_seller) values ('${req.body.book_name}','${req.body.book_cover}','${req.body.book_category_id}','${req.body.book_author}','${req.body.book_press}','${req.body.book_price_yuanjia}','${req.body.book_price_xianjia}','${req.body.book_remarks}','${req.body.book_num}','${req.body.book_date}','${req.body.book_seller}')`
    db.query(sqlStr, (err, results) => {
      if (err) return res.json({ status: 404, message: '上传成功' })
      res.json({ status: 200, message: '上传成功' })
    })
})

module.exports = upload
